package com.tbl.modules.platform.controller.system;

import com.alibaba.fastjson.JSON;
import com.tbl.common.utils.PageData;
import com.tbl.common.utils.PageTbl;
import com.tbl.common.utils.PageUtils;
import com.tbl.common.utils.StringUtils;
import com.tbl.modules.platform.constant.LogActionConstant;
import com.tbl.modules.platform.controller.AbstractController;
import com.tbl.modules.platform.entity.system.Department;
import com.tbl.modules.platform.service.system.DepartmentService;
import com.tbl.modules.platform.service.system.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 部门controller
 * @author 70486
 */
@Controller
@RequestMapping(value = "/dept")
public class DepartmentController extends AbstractController {

    /**
     * 部门service
     */
    @Autowired
    private DepartmentService deptService;
    /**
     * 日志service
     */
    @Autowired
    private LogService logService;


    /**
     * 获取部门列表信息 ：下拉框
     * @param queryString
     * @param pageSize
     * @param pageNo
     * @return Map<String, Object>
     */
    @RequestMapping(value="/getDeptList")
    @ResponseBody
    public Map<String, Object> getDeptList(String queryString, int pageSize, int pageNo){
        Map<String,Object> map = new HashMap<>(7);
        PageTbl page = this.getPage();
        map.put("page",pageNo);
        map.put("limit",pageSize);
        String sortOrder = page.getSortorder();
        if(StringUtils.isEmptyString(sortOrder))
        {
            sortOrder = "desc";
            page.setSortorder(sortOrder);
        }
        map.put("sidx", page.getSortname());
        map.put("order", page.getSortorder());
        map.put("dname", queryString);
        PageUtils pageDept = deptService.getDeptPageList(map);

        map.put("result", deptService.getDepartmentList(map));
        map.put("total", pageDept.getTotalCount());
        return map;
    }


    /**
     * 跳转到用户列表页面
     * @return ModelAndView
     */
    @RequestMapping(value = "/toList.do")
    @ResponseBody
    public ModelAndView list() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("techbloom/platform/system/department/dept_list");
        return mv;
    }

    /**
     * 获取用户列表数据
     * @param deptId
     * @param queryJsonString
     * @return Object
     */
    @RequestMapping(value = "/list.do")
    @ResponseBody
    public Object listUsers(String deptId,String queryJsonString) {
        Map<String,Object> map = new HashMap<>(3);
        //默认显示第一层
        if( StringUtils.isEmptyString(deptId) ) {
            deptId = "0";
        }

        if (!StringUtils.isEmpty(queryJsonString)) {
            map = JSON.parseObject(queryJsonString);
        }

        PageTbl page = this.getPage();
        map.put("page",page.getPageno());
        map.put("limit",page.getPagesize());
        String sortName = page.getSortname();
        if( StringUtils.isEmptyString(sortName) )
        {
            sortName = "user_id";
            page.setSortname(sortName);
        }
        String sortOrder = page.getSortorder();
        if(StringUtils.isEmptyString(sortOrder))
        {
            sortOrder = "desc";
            page.setSortorder(sortOrder);
        }
        map.put("sidx", page.getSortname());
        map.put("order", page.getSortorder());
        map.put("suserid", getSessionUser().getUserId());
        map.put("deptId", Long.valueOf(deptId));
        PageUtils PageUser = deptService.getDeptPageList(map);
        page.setTotalRows(PageUser.getTotalCount()==0?1:PageUser.getTotalCount());
        map.put("rows",PageUser.getList());
        executePageMap(map,page);
        return map;
    }

    /**
     * 根据部门主键获取部门信息
     * @param deptId
     * @return Department
     */
    @RequestMapping(value="/getDeptById")
    @ResponseBody
    public Department getDeptById(Long deptId) {
        Department department = null;
        if (deptId != null) {
            department = deptService.selectById(deptId);
        }
        return department;
    }

    /**
     * 获取部门树
     * @param parentId
     * @return List<Map<String, Object>>
     */
    @RequestMapping(value="/deptTree")
    @ResponseBody
    public List<Map<String, Object>> getPList(Long parentId){
        return deptService.getplist(parentId);
    }

    /**
     * 返回到部门添加/修改页面
     * @return String
     */
    @RequestMapping(value="/dept_edit")
    public String deptAdd() {
        return "techbloom/platform/system/department/dept_edit";
    }

    /**
     * 保存/修改部门
     * @param department
     * @return boolean
     */
    @RequestMapping(value="/save")
    @ResponseBody
    public boolean save(Department department) {
        //标准版本为默认
        department.setEnterpriseId(0L);
        boolean result = deptService.save(department);
        if(result){
            if(department.getDeptId()==null){
                //新增
                logService.logInsert("添加部门[" + department.getDepartmentName() + "]成功！", LogActionConstant.USER_ADD, this.getRequest());
            }else{
                //修改
                logService.logInsert("修改部门[" + department.getDepartmentName() + "]成功！", LogActionConstant.USER_EDIT, this.getRequest());
            }
        }
        return result;
    }

    /**
     * 部门删除
     * @return Object
     */
    @RequestMapping(value="/delDept")
    @ResponseBody
    public Object delDept() {
        Map<String,Object> map = new HashMap<>(2);
        PageData pd = this.getPageData();
        String ids = pd.getString("deptIds");
        StringBuilder msg = new StringBuilder();
        boolean result = false;
        if( !StringUtils.isEmptyString(ids)) {
            List<Department> deptList = deptService.isHasDeptUser(ids);
            //有拥有用户的部门，不能删除
            if( deptList != null && deptList.size() > 0) {
                String deptNames = "";
                for( Department dept : deptList) {
                    deptNames += (StringUtils.isEmptyString(deptNames) ? "" : "，") + dept.getDepartmentName();
                    msg.append("删除部门失败！部门："  + deptNames + "下存在用户，请先删除用户！<br>");
                }
            } else {
                boolean isHasSubDept = deptService.isHasSubDept(ids);
                //存在有子部门的情况
                if(isHasSubDept) {
                    msg.append("有子部门的部门不能删除，请先删除子部门！<br>");
                } else {
                    String names = deptService.getNameByIds(ids);
                    List<Long> lstId = Arrays.asList(ids.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
                    result = deptService.deleteBatchIds(lstId);
                    if(result){
                        logService.logInsert("删除部门["+names+"]成功！", LogActionConstant.USER_DELETE, this.getRequest());
                    }
                }
            }
        }
        map.put("_result", result);
        map.put("deptInfo",msg);
        return map;
    }

    /**
     * 判断是否有相同编号的部门
     * @return Object
     */
    @RequestMapping(value="/hasDeptNo")
    @ResponseBody
    public Object hasDeptNo() {
        String _id = request.getParameter("_id");
        String deptNo = request.getParameter("departmentNo");
        boolean isHas = deptService.hasDeptNo(deptNo,_id);
        return !isHas;
    }

    /**
     * 判断是否有相同名称的部门
     * @return Object
     */
    @RequestMapping(value="/hasDeptName")
    @ResponseBody
    public Object hasDeptName() {
        String _id = request.getParameter("_id");
        String deptName = request.getParameter("departmentName");
        boolean isHas = deptService.hasDeptName(deptName,_id);
        return !isHas;
    }



}
